package start.spring.basic.flowable.service.flowable.impl;

import java.util.ArrayList;
import java.util.List;

import org.flowable.engine.history.HistoricProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import start.spring.basic.flowable.dao.WfCopyMapper;
import start.spring.basic.flowable.entity.WfCopy;
import start.spring.basic.flowable.service.FlowableBaseServiceImpl;
import start.spring.basic.flowable.service.flowable.IWfCopyService;
import start.spring.basic.flowable.service.singletable.WfCopyMpService;
import start.spring.basic.flowable.vo.flowable.WfCopyBo;
import start.spring.basic.flowable.vo.flowable.WfCopyVo;
import start.spring.basic.flowable.vo.flowable.WfTaskBo;
import start.spring.basic.page.PageQuery;
import start.spring.basic.page.PageResult;
import start.spring.basic.response.ResponseData;
import start.spring.basic.ry.core.utils.StringUtils;
import start.spring.basic.util.common.StringUtil;

/**
 * 流程抄送Service业务层处理
 *
 * @author KonBAI
 * @date 2022-05-19
 */
@Service
public class WfCopyServiceImpl extends FlowableBaseServiceImpl implements IWfCopyService {

	@Autowired
    private WfCopyMapper baseMapper;
	
	@Autowired
	private WfCopyMpService wfCopyMpService;

    /**
     * 查询流程抄送
     *
     * @param copyId 流程抄送主键
     * @return 流程抄送
     */
    @Override
    public WfCopy queryById(Long copyId){
        return baseMapper.selectById(copyId);
    }

    /**
     * 查询流程抄送列表
     *
     * @param bo 流程抄送
     * @return 流程抄送
     */
    @Override
    public PageResult<WfCopyVo> selectPageList(WfCopyBo bo, PageQuery pageQuery) {
    	IPage<WfCopy> page = super.getPage(pageQuery);
    	QueryWrapper<WfCopy> queryWrapper = new QueryWrapper<>();
    	queryWrapper.lambda().eq(WfCopy::getUserId, super.getSysUser().getUserId())
    				.like(!StringUtil.isEmpty(bo.getProcessName()), WfCopy::getProcessName, bo.getProcessName())
    				.like(!StringUtil.isEmpty(bo.getOriginatorName()), WfCopy::getOriginatorName, bo.getOriginatorName())
    				.orderByDesc(WfCopy::getCreateTime);
    	page = baseMapper.selectPage(page, queryWrapper);
    	
    	return super.getPageResult(page,WfCopyVo.class);
    }

    @Override
    public Boolean makeCopy(WfTaskBo taskBo) {
        if (StringUtils.isBlank(taskBo.getCopyUserIds())) {
            // 若抄送用户为空，则不需要处理，返回成功
            return true;
        }
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
            .processInstanceId(taskBo.getProcInsId()).singleResult();
        String[] ids = taskBo.getCopyUserIds().split(",");
        List<WfCopy> copyList = new ArrayList<>(ids.length);
        Long originatorId = super.getSysUser().getUserId();
        String originatorName = super.getSysUser().getNickName();
        String title = historicProcessInstance.getProcessDefinitionName() + "-" + taskBo.getTaskName();
        for (String id : ids) {
            Long userId = Long.valueOf(id);
            WfCopy copy = new WfCopy();
            copy.setTitle(title);
            copy.setProcdefId(historicProcessInstance.getProcessDefinitionId());
            copy.setProcessName(historicProcessInstance.getProcessDefinitionName());
            copy.setDeploymentId(historicProcessInstance.getDeploymentId());
            copy.setInstanceId(taskBo.getProcInsId());
            copy.setTaskId(taskBo.getTaskId());
            copy.setUserId(userId);
            copy.setOriginatorId(originatorId);
            copy.setOriginatorName(originatorName);
            copy.setBussinessId(taskBo.getBusinessKey());
            copyList.add(copy);
        }
        return wfCopyMpService.saveBatch(copyList);
    }

	@Override
	public ResponseData<String> deleteCopyList(List<String> ids) {
		QueryWrapper<WfCopy> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(WfCopy::getUserId, super.getSysUser().getUserId())
						.in(WfCopy::getCopyId, ids);
		Integer count = baseMapper.selectCount(queryWrapper);
		if(count==null||count!=ids.size()) {
			return ResponseData.errorMsg("部分抄送记录已不存在，请确认后重新删除！");
		}else {
			baseMapper.delete(queryWrapper);
		}
		return ResponseData.successMsg("记录已删除！");
	}
}
